package cc.laop.support.realm;

import cc.laop.business.system.UserBusiness;
import cc.laop.constants.UserConstants;
import cc.laop.entity.system.Resource;
import cc.laop.entity.system.Role;
import cc.laop.entity.system.User;
import cc.laop.utils.ApplicationUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasAuthenticationException;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.cas.CasToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.util.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;

import java.util.List;
import java.util.Map;

public class AccountRealm extends CasRealm {

    private UserBusiness userBusiness;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthoricationinfo = new SimpleAuthorizationInfo();
        User user = (User) SecurityUtils.getSubject().getSession()
                .getAttribute(UserConstants.CURRENT_USER);
        if (user != null) {
            if (user.getRoleList() != null) {
                for (Role role : user.getRoleList()) {
                    simpleAuthoricationinfo.addRole(role.getName());
                    if (role.getResourceList() != null) {
                        for (Resource resource : role.getResourceList()) {
                            simpleAuthoricationinfo.addStringPermission(
                                    resource.getPermission());
                        }
                    }
                }
            }
        }
        return simpleAuthoricationinfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        CasToken casToken = (CasToken) token;
        if (token == null)
            return null;
        String ticket = (String) casToken.getCredentials();
        if (!StringUtils.hasText(ticket))
            return null;
        TicketValidator ticketValidator = ensureTicketValidator();
        try {
            Assertion casAssertion = ticketValidator.validate(ticket,
                    getCasService());
            AttributePrincipal casPrincipal = casAssertion.getPrincipal();
            String userId = casPrincipal.getName();

            if (userBusiness == null) {
                userBusiness = (UserBusiness) ApplicationUtil
                        .getBean(UserBusiness.class);
            }
            User user = userBusiness.getUserByEmail(userId);
            saveUserSession(user);

            Map<?, ?> attributes = casPrincipal.getAttributes();
            casToken.setUserId(userId);
            String rememberMeAttributeName = getRememberMeAttributeName();
            String rememberMeStringValue = (String) attributes
                    .get(rememberMeAttributeName);
            boolean isRemembered = rememberMeStringValue != null
                    && Boolean.parseBoolean(rememberMeStringValue);
            if (isRemembered)
                casToken.setRememberMe(true);
            List<Object> principals = CollectionUtils
                    .asList(new Object[]{userId, attributes});
            PrincipalCollection principalCollection = new SimplePrincipalCollection(
                    principals, getName());
            return new SimpleAuthenticationInfo(principalCollection, ticket);
        } catch (TicketValidationException e) {
            throw new CasAuthenticationException(
                    (new StringBuilder()).append("Unable to validate ticket [")
                            .append(ticket).append("]").toString(),
                    e);
        }
    }

    public void saveUserSession(User user) {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute(UserConstants.CURRENT_USER, user);
    }

    public UserBusiness getUserBusiness() {
        return userBusiness;
    }

    public void setUserBusiness(UserBusiness userBusiness) {
        this.userBusiness = userBusiness;
    }

}
